package top.syfy.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

/**
 * DOM方式解析XML文件
 *
 */
public class ParseByDom {

    /**
     * 使用Node的方式
     *
     * @param nodes 节点列表
     */
    public static void node(NodeList nodes) {
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node childNode = childNodes.item(j);
                if (Node.ELEMENT_NODE == childNode.getNodeType()) {
                    // 获取节点
                    System.out.print(childNode.getNodeName() + " : ");
                    // 获取节点值
                    System.out.println(childNode.getFirstChild().getNodeValue());
                }
            }
        }
    }

    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        // 创建DocumentBuilderFactory对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 创建DocumentBuilder对象
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("example.xml"));
        NodeList studentList = document.getElementsByTagName("student");
        node(studentList);
    }
}
